package io.renren.modules.newBackground.shanghaiCmcc.v2.client;


import io.renren.modules.newBackground.shanghaiCmcc.v2.util.ConfSerializeUtil;
import org.apache.http.HttpHeaders;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import javax.net.ssl.SSLContext;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.security.KeyStore;
import java.util.Map;


public class OpenapiHttpsCilent {
	private CloseableHttpClient client;
	private String appCode;
	private static String openapisUrl;

	static{
		/*Map<String, String> properties = new ConfSerializeUtil().readConfig("openapi.property");
		
		openapisUrl = properties.get("openapis_server_url");*/
		openapisUrl = "http://211.136.111.133/open/service";
	}
	
	/**
	 * @param appCode
	 *            应用编码
	 * @param keystorePath
	 *            keystore加载路径
	 * @param password
	 *            key密码
	 * @throws Exception
	 */
	public OpenapiHttpsCilent(String appCode, String keystorePath, String password) throws Exception {
		this.appCode = appCode;
		//init();
		KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
		FileInputStream instream = new FileInputStream(new File(keystorePath));
		try {
			trustStore.load(instream, password.toCharArray());
		} finally {
			instream.close();
		}

		SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build();
		SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null,
				SSLConnectionSocketFactory.STRICT_HOSTNAME_VERIFIER);
		this.client = HttpClients.custom().setSSLSocketFactory(sslsf).build();
	}

	/**
	 * @param apiCode
	 *            应用编码
	 * @param transactionId
	 *            业务编码
	 * @param requestBody
	 *            请求报文
	 * @param accessToken
	 *            访问令牌
	 * @return
	 * @throws Exception
	 */
	public String callHttps(String apiCode, String transactionId, String requestBody, String accessToken) throws Exception {
		HttpPost httpPost = null;
		CloseableHttpResponse response = null;
		String tmp = null;
		try {
			httpPost = new HttpPost(openapisUrl + "/accessHttps");
			httpPost.addHeader("appCode", appCode);
			httpPost.addHeader("apiCode", apiCode);
			httpPost.addHeader("transactionId", transactionId);
			httpPost.addHeader("accessToken", accessToken);
			httpPost.addHeader("sdkVersion", "sdk.version.2.2");
			httpPost.addHeader(HttpHeaders.CONNECTION, "close");
			httpPost.setEntity(new StringEntity(requestBody, ContentType.create("text/plain", "UTF-8")));
			response = client.execute(httpPost);
			InputStreamReader isr = new InputStreamReader(response.getEntity().getContent(),"UTF-8");
			BufferedReader br = new BufferedReader(isr);
			StringBuffer sb = new StringBuffer();
			while ((tmp = br.readLine()) != null) {
				sb.append(tmp);
			}
			String responseBody = sb.toString();
			return responseBody;
		} finally {
			if (response != null) {
				response.close();
			}
			if (httpPost != null) {
				httpPost.abort();
			}
		}
	}

	/**
	 * @param apiCode
	 *            能力编码
	 * @param transactionId
	 *            业务编码
	 * @param requestBody
	 *            请求报文
	 * @return
	 * @throws Exception
	 */
	public String callHttps(String apiCode, String transactionId, String requestBody) throws Exception {
		return callHttps(apiCode, transactionId, requestBody, null);
	}

	private void init() {
		Map<String, String> properties = new ConfSerializeUtil().readConfig("openapi.property");
		openapisUrl = "http://211.136.111.133/open/service";
	}

}
